import 'package:flutter/material.dart';
import 'package:rxdart/subjects.dart';

class RxDartDemoPage extends StatefulWidget {
  RxDartDemoPage({Key key}) : super(key: key);

  @override
  _RxDartDemoPageState createState() => _RxDartDemoPageState();
}

class _RxDartDemoPageState extends State<RxDartDemoPage> {
  PublishSubject _textFieldSubject;
  @override
  void initState() {
    super.initState();

    _textFieldSubject = PublishSubject<String>();
    _textFieldSubject
        // 延迟 (实际快速输入时 只监听到 1s 内最后一次输入)
        .debounce(Duration(seconds: 1))
        // 修改数据
        .map((value) => '>' + value)
        // 过滤数据, (大于 5 时才会调用 listen), 比如搜索内容长度不够时每次发起网络请求将浪费
        .where((value) => value.length > 5)
        // 监听到数据
        .listen((data) => print(data));
  }

  @override
  void dispose() {
    super.dispose();
    _textFieldSubject.close();
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        ListTile(
          title: Text('PublishSubject'),
          subtitle: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Text('''
- debounce;
- map;
- where;
- listen;
              '''),
              ),
              TextField(
                decoration: InputDecoration(
                  hintText: 'User Name',
                ),
                onChanged: (value) {
                  _textFieldSubject.add(value);
                },
                onSubmitted: (value) {
                  _textFieldSubject.add(value);
                },
              ),
            ],
          ),
        )
      ],
    );
  }
}
